package com.rfsp.common.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: crush
 * @Date: 2021-07-29 15:26
 * version 1.0
 */
@RestController
@RequestMapping("/dynamicTask")
public class DynamicTaskController {

    static final Logger logger = LoggerFactory.getLogger(DynamicTaskController.class);

    @Resource
    DynamicTaskService dynamicTask;


    /**
     * 查看已开启但还未执行的动态任务
     * @return
     */
    @GetMapping
    public List<String> getScheduledList(){
        return dynamicTask.getTaskList();
    }


    /**
     * 开启一个动态任务
     * @return
     */
    @PostMapping("/startTask1")
    public String startDynamicTask(){
        Runnable r = dynamicTask.getTestTask();
        Date startTime = new Date();
        String id = "id_001";

        // 将这个添加到动态定时任务中去
        dynamicTask.start(r, startTime, id);
        return "动态任务:"+id+" 已开启";
    }


    /**
     *  根据名称 停止一个动态任务
     * @param id
     * @return
     */
    @DeleteMapping("/stopTask2/{name}")
    public String stopDynamicTask(String id){
        if(!dynamicTask.stop(id)){
            return "停止失败,任务已在进行中.";
        }
        return "任务已停止";
    }


    @PostMapping("/startTask2")
    public String startTask2(){

        Runnable r = dynamicTask.getTestTask();
        String cron = "*/6 * * * * ?";
        String id = "id_002";

        dynamicTask.add(r, cron, id);

        return "动态任务:"+id+" 已开启";
    }


    @PostMapping("/stopTask2")
    public String stopTask2(String id){
        if(!dynamicTask.remove(id)){
            return "停止失败,任务已在进行中.";
        }
        return "任务:"+id+" 已停止";
    }


}
